package com.house.keeper.shiro.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.house.keeper.constant.ConstantConfig;
import com.house.keeper.entity.Menu;
import com.house.keeper.entity.Role;
import com.house.keeper.entity.User;
import com.house.keeper.mapper.MenuMapper;
import com.house.keeper.mapper.RoleMapper;
import com.house.keeper.mapper.UserMapper;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 身份校验核心类
 *
 * @author zjj
 * @date 2022-05-09
 */
@Service //标记为业务逻辑类
public class MyShiroRealm extends AuthorizingRealm {

    @Autowired //标记spring将要解析和注入的依赖项
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private MenuMapper menuMapper;

    /**
     * 授权查询回调函数
     * 进行鉴权
     * 缓存中没有用户的授权信息的时候进行调用
     * @param principalCollection
     * @return
     */
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        if(principalCollection == null){
            throw new AuthenticationException("principalCollection should not be null");
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();

        User userInfo = (User)principalCollection.getPrimaryPrincipal();
        int uid = userInfo.getId();
//        TODO 根据用户id查询角色
        List<Role> tRoles= roleMapper.queryRoleByUserId(uid);
        for (Role role:tRoles) {
            authorizationInfo.addRole(role.getRoleName());//添加角色名称

            int roleId = role.getId();
//        TODO 根据角色id查询菜单
            List<Menu> tMenus = menuMapper.queryMenuByRoleId(roleId);
            for (Menu menu:tMenus) {
                if(StringUtils.isNotEmpty(menu.getMenuPerms())){
                    authorizationInfo.addStringPermission(menu.getMenuPerms());
                }
            }
        }
        return authorizationInfo;
    }

    /**
     * 认证登录
     * @param token 登录认证的标识
     * @return
     * @throws AuthenticationException
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
//        在post请求的时候，先进行认证，然后再到请求
        if(token.getPrincipal() == null){
            return null;
        }
        String userName = (String)token.getPrincipal();
//        String password = new String((char[])token.getCredentials());
        QueryWrapper<User> wrapper = new QueryWrapper();
        wrapper.eq("user_name",userName);
        wrapper.eq("user_status", ConstantConfig.STATUS_YES);
        User userInfo=userMapper.selectOne(wrapper);
        if(userInfo == null){
            return null;
        }else{
            return new SimpleAuthenticationInfo(
                    userInfo,//用户对象
                    userInfo.getUserPwd(),//密码
                    getName()//realm name
            );
        }
    }

    /**
     * 清理缓存权限
     */
   public void clearCacheAuthorizationInfo(){
        this.clearCachedAuthorizationInfo(SecurityUtils.getSubject().getPrincipals());
   }
}
